package com.sgb.kjwl.viewmodel.self.packers;

import android.view.View;

import androidx.core.content.ContextCompat;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.WorkerLevel;
import com.sgb.kjwl.model.entity.self.SelfEmploymentEditEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.view.ui.activity.self.packers.SelfTeamEmploymentEditActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SelfTeamEmploymentEditModel extends BaseViewModel {

    private SelfTeamEmploymentEditActivity activity;
    private SelfRepertory selfRepertory;
    private List<PickSelectEntity> listFs;
    private int firstPosition,secondPosition;

    public SelfTeamEmploymentEditModel(SelfTeamEmploymentEditActivity activity, SelfRepertory selfRepertory) {
        this.activity = activity;
        this.selfRepertory = selfRepertory;
    }

    public void detailEmployment(String no) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().detailEmployment(no).enqueue(new Callback<BaseEntity<SelfEmploymentEditEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<SelfEmploymentEditEntity>> call, Response<BaseEntity<SelfEmploymentEditEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    activity.updateTeamEmploymentEntity(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<SelfEmploymentEditEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    public void uploadEmployment(SelfEmploymentEditEntity entity) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().uploadEmployment(entity).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    activity.uploadEmploymentResult();
                } else {
                    MToast.showLongToast(activity, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                activity.uploadFail();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
                MToast.showLongToast(activity, "发布失败");
            }
        });
    }

    public void getAddressModel() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getGoodsAPI().getCityList().enqueue(new Callback<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Response<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if ("200".equals(response.body().getCode())) {
                    activity.showAddressPop(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MLog.d(AppConstant.API_LOG, "error " + t.getMessage());
            }
        });
    }

    // ------------------------------------------用工类型 -----------------------------------------------
    public void getEmploymentType() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPackerAPI().getEmploymentType().enqueue(new Callback<BaseEntity<List<WorkerLevel>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<WorkerLevel>>> call, Response<BaseEntity<List<WorkerLevel>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<WorkerLevel> workYears = response.body().getData();
                    List<PickSelectEntity> data = new ArrayList<>();
                    if (workYears != null && workYears.size() > 0) {
                        for (WorkerLevel workerLevel : workYears) {
                            PickSelectEntity entity = new PickSelectEntity();
                            entity.setNo(String.valueOf(workerLevel.getType()));
                            entity.setProjectscale(workerLevel.getDesc());
                            data.add(entity);
                        }
                    }
                    data.remove(0);
                    activity.showPickWorkerTypePop(data);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<WorkerLevel>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    // ------------------------------------------用工状态 -----------------------------------------------
    public void getEmploymentStatus() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPackerAPI().getEmploymentStatus().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<PickSelectEntity> data = response.body().getData();
                    if (data == null || data.size() == 0) {
                        data = new ArrayList<>();
                    }
                    data.remove(0);
                    activity.showPickWorkerStatusPop(data);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    // -------------------------------------------获取相册照片--------------------------------------------------
    public void pictureSelector(int number, int requestCode) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.MULTIPLE)
                .compress(true)//是否压缩
                .minimumCompressSize(10240)//小于10M不压缩
                .maxSelectNum(number)//判断还能选多少张图片
                .forResult(requestCode);
    }

    public void uploadMultiFileModel(File file, int completeNum, int imgTotal) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + completeNum + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(activity, null, "图片上传中" + completeNum + "/" + imgTotal + "...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.uploadPicInfo(file.getAbsolutePath(), response.body().getData().toString());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity, t.getMessage());
            }
        });
    }

    // -------------------------------------------工时-单位--------------------------------------------------
    public void getEmploymentUnit() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPackerAPI().getEmploymentUnit().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<PickSelectEntity> data = response.body().getData();
                    if (data == null || data.size() == 0) {
                        data = new ArrayList<>();
                    }
                    activity.showPickEmploymentUnitPop(data);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    // ------------------------------------------薪资单位 -----------------------------------------------
    public void getEmploymentSalaryUnit() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getEmploymentSalaryUnit().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.showEmploymentSalaryUnitPop(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    // ------------------------------------------薪资方式 -----------------------------------------------
    public List<PickSelectEntity> getSalaryFs() {
        if (listFs == null) {
            listFs = new ArrayList<>();
            PickSelectEntity entity1 = new PickSelectEntity();
            entity1.setNo("3");
            entity1.setProjectscale("自定义薪资");
            PickSelectEntity entity2 = new PickSelectEntity();
            entity2.setNo("2");
            entity2.setProjectscale("电议");
            PickSelectEntity entity3 = new PickSelectEntity();
            entity3.setNo("1");
            entity3.setProjectscale("面议");
            listFs.add(entity1);
            listFs.add(entity3);
            listFs.add(entity2);
        }
        return listFs;
    }

    // ------------------------------------------咨询客服 -----------------------------------------------
    private OptionsPickerView<PickSelectEntity> mCustomerOptions; // 咨询客服
    private List<PickSelectEntity> mServiceList = new ArrayList<>();

    public void getCustomerData(boolean isShow) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getMachineAPI().getCustomerOrg()
                .enqueue(new Callback<BaseEntity<List<ServiceEntity>>>() {
                             @Override
                             public void onResponse(Call<BaseEntity<List<ServiceEntity>>> call, Response<BaseEntity<List<ServiceEntity>>> response) {
                                 DialogHelper.dismissProgressDialog();
                                 if (response.body() == null || response.body().getState() == null) {
                                     return;
                                 }
                                 if (response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                                     List<ServiceEntity> data = response.body().getData();
                                     if (data == null || data.size() == 0) {
                                         return;
                                     }
                                     mServiceList = new ArrayList<>();
                                     for (int i = 0; i < data.size(); i++) {
                                         PickSelectEntity pickSelectEntity = new PickSelectEntity();
                                         pickSelectEntity.setNo(data.get(i).getId());
                                         pickSelectEntity.setProjectscale(data.get(i).getName());
                                         mServiceList.add(pickSelectEntity);
                                     }
                                     if (isShow) {
                                         showCustomerPop();
                                     }
                                 }
                             }

                             @Override
                             public void onFailure(Call<BaseEntity<List<ServiceEntity>>> call, Throwable t) {
                                 DialogHelper.dismissProgressDialog();
                             }
                         }
                );
    }

    // 咨询客服
    public void showCustomerPop() {
        if (mServiceList == null || mServiceList.size() == 0) {
            getCustomerData(true);
            return;
        }
        mCustomerOptions = new OptionsPickerBuilder(activity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                activity.updateCustomer(mServiceList.get(options1));
            }
        }).setCancelColor(ContextCompat.getColor(activity, R.color.color_666666)).setTitleColor(ContextCompat.getColor(activity, R.color.color_969696)).build();
        mCustomerOptions.setTitleText("选择咨询客服");
        mCustomerOptions.setPicker(mServiceList);
        mCustomerOptions.setSelectOptions(0);
        mCustomerOptions.show();
    }

    /**
     * 获取经纬度信息
     * @param no
     * @param cityNo
     * @param areaNo
     */
    public void getLocationLL(String no, String cityNo, String areaNo) {
        DialogHelper.showProgressDialog(activity, null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getLocationLL(selfRepertory.getAreaCode(), no, cityNo, areaNo).enqueue(new Callback<BaseEntity<MapLongAndLatEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<MapLongAndLatEntity>> call, Response<BaseEntity<MapLongAndLatEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    activity.updateAddress(response.body().getData());
                } else {
                    MToast.showToast(activity.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<MapLongAndLatEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(activity.getActivity(), t.getMessage());
            }
        });

    }

    // -------------------------------- 服务团队-联动工种 --------------------------------
    private OptionsPickerView<PickSelectEntity> mIndustryOptions;
    private List<PickSelectEntity<List<PickSelectEntity>>> mOpt;
    private List<PickSelectEntity> mOpt1 = new ArrayList<>();//工程分类
    private List<List<PickSelectEntity>> mOpt2 = new ArrayList<>();//劳务分类
    public int opt1;
    public int opt2;

    public void getIndustryData(boolean isShow) {
        DialogHelper.showProgressDialog(activity, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getIndustryData().
                enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null || response.body().getState() == null) {
                            return;
                        }

                        if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                            mOpt = response.body().getData();
                            if (mOpt == null || mOpt.size() == 0) {
                                return;
                            }
                            mOpt = response.body().getData();
                            mOpt1.clear();
                            mOpt1.addAll(mOpt);
                            mOpt2.clear();
                            for (PickSelectEntity<List<PickSelectEntity>> provinceDatum : mOpt) {
                                List<PickSelectEntity> children = provinceDatum.getChildren();
                                mOpt2.add(children);
                            }
                            if (isShow) {
                                showIndustryPop();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                    }
                });
    }

    public void showIndustryPop() {
        if (mOpt1 == null || mOpt1.size() == 0) {
            getIndustryData(true);
            return;
        }
        if (mIndustryOptions == null) {
            mIndustryOptions = new OptionsPickerBuilder(activity, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    if (mOpt2.get(options1).size() != 0){
                        activity.selectedIndustry(mOpt.get(options1), mOpt2.get(options1).get(options2));
                        firstPosition = options1;
                        secondPosition = options2;
                    }else {
                        PickSelectEntity pickSelectEntity = new PickSelectEntity();
                        pickSelectEntity.setNo("");
                        pickSelectEntity.setProjectscale("");
                        activity.selectedIndustry(mOpt.get(options1), pickSelectEntity);
                        firstPosition = options1;
                        secondPosition = -1;
                    }
                    opt1 = options1;
                    opt2 = options2;
                }
            }).setCancelColor(ContextCompat.getColor(activity, R.color.color_666666)).setTitleColor(ContextCompat.getColor(activity, R.color.color_969696)).build();
            mIndustryOptions.setTitleText("选择专业要求");
        }
        mIndustryOptions.setPicker(mOpt1, mOpt2);
        mIndustryOptions.setSelectOptions(opt1, opt2);
        mIndustryOptions.show();
    }

    // -------------------------------------------服务团队-工种分类-------------------------------------------
    public void getWorkType() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getTeamNewInterfaceAPI().getLinkAgeWorkType().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                if (data.isSuccess()) {
                    if (secondPosition != -1){
                        activity.showPickWorkTypePop(data.getData().get(firstPosition).getChildren().get(secondPosition).getChildren());
                    }
                }
            }
        });
    }

}
